;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Account.MonthlyFinanceCheck", [])
        .controller("MonthlyFinanceCheckCtrl", ["$scope", "ybWidget", "ybHttp", "MESG_TYPE", "UserContextService", "$timeout", "$filter", function ($scope, ybWidget, ybHttp, MESG_TYPE, UserContextService, $timeout, $filter) {
            $scope.handleMultiInput = function(e) {
                $scope.condition.dealerName = UserContextService.MultiInput(e.target.value);
            };

            $scope.tabFlag = {};
            var tabFlag = {
                0: "新增",
                1: "编辑"
            };

            // 列表查询条件
            $scope.condition = {
                dealerFlag: $scope.isZHJCH ? 0 : 1
            };
            // 表格列配置信息
            $scope.toolbarConfig = {};
            // 表格信息
            $scope.tableConfig = {
                fixedWidth: 80,
                scrollWidth: 3000,
                tableCol: [
                    {
                        name: "代理商名称",
                        dataField: "dealerName",
                        width: 200,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "确认状态",
                        dataField: "stateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "确认人",
                        dataField: "auditName",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "确认时间",
                        dataField: "auditTimeShow",
                        width: 140,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "确认说明",
                        dataField: "remark",
                        width: 140,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "对账人",
                        dataField: "reconciliateName",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "对账月份",
                        dataField: "reconciliateDateShow",
                        width: 80,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "对账当月初备件欠款",
                        dataField: "lastMonthDebt",
                        width: 140,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "对账当月回款合计",
                        dataField: "lastMonPayment",
                        width: 140,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "现金回款小计",
                        dataField: "cashPayment",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "现金汇款",
                        dataField: "cashTransfer",
                        width: 120,
                        isShow: false,
                        isFixed: false
                    },
                    {
                        name: "转服务费",
                        dataField: "tranServiceCharge",
                        width: 120,
                        isShow: false,
                        isFixed: false
                    },
                    {
                        name: "转材料费",
                        dataField: "tranMaterialsCharge",
                        width: 120,
                        isShow: false,
                        isFixed: false
                    },
                    {
                        name: "转备件政策返利",
                        dataField: "policyRebate",
                        width: 120,
                        isShow: false,
                        isFixed: false
                    },
                    {
                        name: "破碎锤融资放款",
                        dataField: "financialLend",
                        width: 120,
                        isShow: false,
                        isFixed: false
                    },
                    {
                        name: "转微挖服务费",
                        dataField: "tranWwServiceCharge",
                        width: 120,
                        isShow: false,
                        isFixed: false
                    },
                    {
                        name: "转微挖材料费",
                        dataField: "tranWwMaterialCharge",
                        width: 120,
                        isShow: false,
                        isFixed: false
                    },
                    {
                        name: "其他费用冲抵",
                        dataField: "otherChargeOffset",
                        width: 120,
                        isShow: false,
                        isFixed: false
                    },
                    {
                        name: "服务费冲抵",
                        dataField: "serviceChargeOffset",
                        width: 120,
                        isShow: false,
                        isFixed: false
                    },
                    {
                        name: "对账当月工厂开票",
                        dataField: "lastMonInvoice",
                        width: 140,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "调拨代理商开票",
                        dataField: "dealerAllotInvoice",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "调拨徐工开票",
                        dataField: "xcmgAllotInvoice",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "对账当月底备件欠款",
                        dataField: "lastMonthEndDebt",
                        width: 140,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "信用额度",
                        dataField: "creditLimit",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "对账当月底逾期金额",
                        dataField: "lastMonthEndOverdue",
                        width: 140,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "本月回款任务",
                        dataField: "paymentTask",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "已开票未发货",
                        dataField: "unshipped",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "创建时间",
                        dataField: "createDateShow",
                        width: 140,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "大区",
                        dataField: "reserve2",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "代理商性质",
                        dataField: "reserve3",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 80,
                        isShow: true,
                        isFixed: true
                    }
                ]
            };
            // 切换配置表格列展示隐藏
            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                    return;
                }
                $timeout(function () {
                    $scope.toolbarConfig["show" + toolbar] = true;
                });
            };
            // 设置表格宽度
            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: { left: $scope.tableConfig.fixedWidth + "px" }
                };
            };
            // 当前选中行
            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };

            $scope.markInfo = {
                curRow: -1
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.dataList = [];

            $scope.search = function (curPage) {
                if (curPage) $scope.pageInfo.curPage = curPage;
                getDataList();
            };
            function getDataList() {
                var url = '/reconciliation/list';

                var param = {
                    filters: angular.copy($scope.condition),
                    pageSize: $scope.pageInfo.pageSize,
                    pageNum: $scope.pageInfo.curPage,
                };
                ybHttp.Post('device', url, param).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    if (!res.value) return;

                    angular.forEach(res.value.list, function (item) {
                        item.stateShow = $filter("ProgressStatus")(item.state, "reconciliationStatus");
                        item.auditTimeShow = $filter("YbDate")(item.auditTime, 'yyyy-MM-dd HH:mm:ss');
                        item.reconciliateDateShow = $filter("YbDate")(item.reconciliateDate, 'yyyy-MM');
                        item.createDateShow = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                    });

                    $scope.pageInfo.totalRows = res.value.total;
                    $scope.pageInfo.totalPages = res.value.pages;
                    $scope.dataList = res.value.list;
                });
            }


            $scope.reset = function () {
                $scope.condition = {
                    dealerFlag: $scope.isZHJCH ? 0 : 1
                };
            };

            $scope.detailInfo = {};

            // 切换标签页
            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        $scope.detailInfo = {};
                        break;
                    default:
                        break;
                }
            };

            $scope.addData = function () {
                $scope.tabFlag.type = 0;
                $scope.tabFlag.name = tabFlag[0];
                $scope.changeTab(1);
            };

            $scope.editData = function (item) {
                $scope.tabFlag.type = 1;
                $scope.tabFlag.name = tabFlag[1];
                $scope.detailInfo = JSON.parse(JSON.stringify(item));
                if ($scope.detailInfo.reconciliateDate) {
                    $scope.detailInfo.reconciliateDate = new Date($scope.detailInfo.reconciliateDate);
                }
                $scope.changeTab(1);
            };

            $scope.delData = function (item) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function (data) {
                    var url = '/reconciliation/delete';
                    ybHttp.Post('device', url, [item.id]).then(function (res) {
                        if (res.code !== 0) {
                            ybWidget.ShowMessage(res, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        $scope.search(1);
                    });
                })
            };

            $scope.signData = function (item) {
                ybWidget.AuditMsg({
                    title: '确认',
                    validateCb: function(val, otherData) {
                        if (!otherData.reconciliateId) {
                            ybWidget.ShowMessage("请选择对账人", MESG_TYPE.Error);
                            return false;
                        }

                        if (!val) {
                            ybWidget.ShowMessage("请输入确认意见", MESG_TYPE.Error);
                            return false;
                        }
                        return true;
                    },
                    passCb: function(val, otherData) {
                        return handleSign(item.id, val, 1, otherData);
                    },
                    refuseCb: function(val, otherData) {
                        return handleSign(item.id, val, 2, otherData);
                    }
                })
            };

            function handleSign (id, remark, state, otherData) {
                const param = {
                    id, remark, state,
                    ...otherData
                }
                return ybHttp.Post('device', '/reconciliation/receiptIn', param).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.search(1);
                });
            }

            // 选择代理商
            $scope.selectDealer = function () {
                var param = {
                    name: "代理商",
                    type: "dealer",
                    isPlatCompany: 1
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.detailInfo.dealerName = data.companyName;
                    $scope.detailInfo.dealerOrgId = data.platOrgId;
                })
            };

            // 保存
            $scope.saveData = UserContextService.Debounce(function (argu) {
                saveDataFunc(argu);
            }, 500);

            function saveDataFunc (valid) {
                if (!valid) {
                    $scope.submitted = true;
                    return;
                }
                var url = $scope.tabFlag.type == 0 ? '/reconciliation/add' : '/reconciliation/update';
                var param = angular.extend($scope.detailInfo);
                ybHttp.Post('device', url, param).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.search(1);
                    $scope.changeTab(0);
                });
            };

            // 取消
            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            // 导入
            $scope.importData = function () {
                var param = {
                    name: "对账信息",
                    templateReqService: "device",
                    templateReqUrl: "/reconciliation/downloadExcel",
                    importReqService: "device",
                    importReqUrl: "/reconciliation/importExcel",
                    importErrorUrl: ""
                };
                ybWidget.ImportFile(param).then(function (data) {
                    $scope.search(1);
                });
            };

            // 导出
            $scope.exportParam = {
                allUrl: ybHttp.RequestUrl("device", "/reconciliation/exportReconciliation")
            };

            // 现金回款小计
            $scope.handleCashPayment = function () {
                const val = Number($scope.detailInfo.cashTransfer||0)
                            + Number($scope.detailInfo.tranServiceCharge||0)
                            + Number($scope.detailInfo.tranMaterialsCharge||0)
                            + Number($scope.detailInfo.policyRebate||0)
                            + Number($scope.detailInfo.financialLend||0)
                            + Number($scope.detailInfo.tranWwServiceCharge||0)
                            + Number($scope.detailInfo.tranWwMaterialCharge||0);
                $scope.detailInfo.cashPayment = $filter("decimalCover")(val, 2);

                $scope.handleLastMonPayment(); // 现金回款小计 改变后 重新计算 对账当月回款合计
            };

            // 对账当月回款合计
            $scope.handleLastMonPayment = function () {
                const val = Number($scope.detailInfo.cashPayment||0)
                            + Number($scope.detailInfo.otherChargeOffset||0)
                            + Number($scope.detailInfo.serviceChargeOffset||0);
                $scope.detailInfo.lastMonPayment = $filter("decimalCover")(val, 2);

                $scope.handleLastMonthEndDebt(); // 对账当月回款合计 改变后 重新计算 对账当月底备件欠款
            };

            // 对账当月底备件欠款
            $scope.handleLastMonthEndDebt = function () {
                const val = Number($scope.detailInfo.lastMonthDebt||0)
                            + Number($scope.detailInfo.lastMonInvoice||0)
                            + Number($scope.detailInfo.xcmgAllotInvoice||0)
                            - Number($scope.detailInfo.dealerAllotInvoice||0)
                            - Number($scope.detailInfo.lastMonPayment||0);
                $scope.detailInfo.lastMonthEndDebt = $filter("decimalCover")(val, 2);
            };

            $scope.toggleCashPaymentShow = function(flag) {
                ybWidget.GetTableCol($scope.tableConfig.tableCol, 'cashTransfer').isShow = flag;
                ybWidget.GetTableCol($scope.tableConfig.tableCol, 'tranServiceCharge').isShow = flag;
                ybWidget.GetTableCol($scope.tableConfig.tableCol, 'tranMaterialsCharge').isShow = flag;
                ybWidget.GetTableCol($scope.tableConfig.tableCol, 'policyRebate').isShow = flag;
                ybWidget.GetTableCol($scope.tableConfig.tableCol, 'financialLend').isShow = flag;
                ybWidget.GetTableCol($scope.tableConfig.tableCol, 'tranWwServiceCharge').isShow = flag;
                ybWidget.GetTableCol($scope.tableConfig.tableCol, 'tranWwMaterialCharge').isShow = flag;
            };
            $scope.toggleLastMonPaymentShow = function(flag) {
                ybWidget.GetTableCol($scope.tableConfig.tableCol, 'otherChargeOffset').isShow = flag;
                ybWidget.GetTableCol($scope.tableConfig.tableCol, 'serviceChargeOffset').isShow = flag;
            };

            // 初始化页面信息
            (function () {
                if (!$scope.isZHJCH) {
                    $scope.tableConfig.tableCol.splice($scope.tableConfig.tableCol.length - 3, 2)
                }
                $scope.setFixedWidth();
                $scope.search(1);
            })()
        }])
        ;
})(window, window.angular);